<template>
	<div class="json-editor-box">
		<!-- 数据回来再渲染，避免第一次 new 时无 schema -->
		<div
			v-if="schema"
			ref="editorRef"
			class="json-editor-wrap"
			:class="{ pseudoFullScreen: isFull }"
			style="height: 500px"
		></div>
		<el-button class="json-editor-save-btn" type="primary" @click="saveJson">保存</el-button>
	</div>
</template>

<script setup>
import {ref, onMounted, onUnmounted, watch, inject,watchEffect} from 'vue'
import { createJSONEditor } from 'vanilla-jsoneditor/standalone.js'
import { createAjvValidator } from 'vanilla-jsoneditor/standalone.js'
const  { formData } = inject('sharedData')

import { ElMessage } from 'element-plus'
//import { getSituationStatusData } from '@/api/screen/overview.js'
import data from './json.js'
const editorRef = ref(null)
const content = ref({
	json: null,
	text: undefined
})
const schema = ref(null)
const isFull = ref(false)
let editor = null



// 只锁字段名 & 类型 Schema
const getSchema = (obj) => {
	if (Array.isArray(obj)) {
		return obj.length
			? { type: 'array', contains: getSchema(obj[0]) }
			: { type: 'array', items: {} }
	}
	if (obj !== null && typeof obj === 'object') {
		const s = {
			type: 'object',
			properties: {},
			additionalProperties: false,
			required: Object.keys(obj)
		}
		for (const [k, v] of Object.entries(obj)) s.properties[k] = getSchema(v)
		return s
	}
	return { type: typeof obj }
}

// 异步加载 → 第一次就带有效 schema
const loadData = async () => {
	//const res = await getSituationStatusData({ timeMode: 'day', orgId: '' })
	const res = JSON.parse(JSON.stringify(formData)) // 深拷贝解构
	console.log('formData', res)
	schema.value = getSchema(res)
	content.value = { json: res }
}

// 新增全屏按钮
const addFullScreenButton = () => {
	const header = editorRef.value.querySelector('.jse-menu') // 顶部菜单栏
	if (!header) return

	// 创建全屏按钮元素
	const fsBtn = document.createElement('button')
	fsBtn.className = 'jse-button jse-fullscreen iconfont icon-quanping1'
	fsBtn.title = '进入全屏'
	fsBtn.onclick = () => (isFull.value = !isFull.value)
	header.appendChild(fsBtn)
}

// 挂载编辑器（schema 已有效）
const initEditor = () => {
	// 创建 ajv 校验器
	const validator = createAjvValidator({ schema: schema.value, schemaRefs: {} })
	editor = createJSONEditor({
		target: editorRef.value,
		props: {
			content: content.value,
			mode: 'text',
			validator, // ajv 实时校验器
			mainMenuBar: true,
			// 自定义菜单项
			onRenderMenu: (items) => {
				// 目前尚未支持国际化，各个按钮的 title 需手动设置成中文
				const zhTitles = {
					'jse-format': '格式化JSON：添加正确的缩进和换行符（Ctrl+I）',
					'jse-compact': '紧凑JSON：移除所有空白和换行符（Ctrl+Shift+I）',
					'jse-undo': '撤销（Ctrl+Z）',
					'jse-redo': '重做（Ctrl+Shift+Z）'
				}
				// 只展示格式化、紧凑、撤销、重做这些按钮
				return items
					.filter(item => item.type === 'button' && ['jse-format', 'jse-compact', 'jse-undo', 'jse-redo'].includes(item.className))
					.map(item => ({
						...item,
						title: zhTitles[item.className]
					}))
			},
			onChange: (updatedContent) => {
				content.value = updatedContent
			}
		}
	})
	// 在 createJSONEditor 之后再添加全屏按钮，否则找不到 header 元素
	addFullScreenButton()

	// 新增监听：当 content 变化时，主动更新编辑器
	watch(
		() => formData,
		(newVal) => {
			if (!editor || !newVal) return;
			// 深拷贝避免响应式 Proxy 问题
			const dataCopy = JSON.parse(JSON.stringify(newVal));
			// setTimeout 确保 DOM 已完成更新
			setTimeout(() => {
				editor.update({ json: dataCopy });
			}, 50); // 50ms 延迟通常足够
		},
		{ deep: true }
	);
}

// 保存再校验一次
const saveJson = async () => {
	const res = await editor.validate()
	const errors = res?.validationErrors ?? []   // 取数组再判断
	if (errors?.length) {
		ElMessage.error('字段名或层级结构被改动，请恢复后再保存！')
		return
	}
	const finalJson = content.value.json || JSON.parse(content.value.text || '{}')

	console.log('数据保存成功', finalJson)

	//const jsonData = JSON.parse(content.value.json)
	formData.value = finalJson
	// 用户修改后调接口进行保存
	ElMessage.success('数据保存成功')
}

watch(isFull, val => {
	const btn = editorRef.value?.querySelector('.jse-button.jse-fullscreen')
	if (!btn) return
	btn.className = `jse-button jse-fullscreen iconfont ${val ? 'icon-tuichuquanping' : 'icon-quanping1'}`
	btn.title = val ? '退出全屏' : '进入全屏'
})

onMounted(async () => {
	await loadData()   // 先拿数据
	initEditor()       // 再挂载编辑器（带有效 schema）
})

onUnmounted(() => {
	if (editor) {
		editor.destroy()
		editor = null
	}
})
</script>

<style scoped>
/* ✅ 正确写法：用 :deep() 穿透动态类名 */
:deep(.jse-menu) {
	background: #f5a21d !important;
}
:deep(.jse-menu button) {
	color: white !important;
}


/* 伪全屏样式 */
.json-editor-wrap.pseudoFullScreen {
	position: fixed;
	inset: 0;
	z-index: 1501;
	background: #fff;
	padding: 20px;
	height: 100vh !important;
}

:deep(.jse-button.jse-fullscreen) {
	margin-left: auto;
	background: none;
	border: none;
	font-size: 20px;
	color: #fff;
	cursor: pointer;
}

.json-editor-save-btn {
	margin-top: 12px;
}
</style>
